import Menu from 'ant-design-vue/es/menu'
import Icon from 'ant-design-vue/es/icon'
import Vue from 'vue'
import { POUNDLIST, MATERIABOOK, CONTRACT, MenuSelect, PERMMISSION_LIST } from '@/store/mutation-types'

const { Item, SubMenu } = Menu

export default {
  name: 'SMenu',
  props: {
    menu: {
      type: Array,
      required: true
    },
    theme: {
      type: String,
      required: false,
      default: 'dark'
    },
    mode: {
      type: String,
      required: false,
      default: 'inline'
    },
    collapsed: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  data() {
    return {
      openKeys: [],
      selectedKeys: [],
      cachedOpenKeys: [],
      selectMenuAnt: "",
      state: 1,
      menuSelect: 0
    }
  },
  computed: {
    rootSubmenuKeys: vm => {
      const keys = []
      vm.menu.forEach(item => keys.push(item.path))
      return keys
    }
  },
  mounted() {
    this.updateMenu()
  },
  watch: {
    collapsed(val) {
      if (val) {

        this.cachedOpenKeys = this.openKeys.concat()
        this.openKeys = []
      } else {

        this.openKeys = this.cachedOpenKeys
      }
    },
    $route: function () {
      this.updateMenu()
    }
  },
  methods: {

    filterPermissMainIndex(menukey) {

      for (let index = 0; index < Vue.ls.get(PERMMISSION_LIST).length; index++) {
        if (menukey == Vue.ls.get(PERMMISSION_LIST)[index]) {
          return true
        }
        if ('admin' == Vue.ls.get(PERMMISSION_LIST)[index]) {
          return true
        }

      }
    },
    onOpenChange(openKeys) {
      const latestOpenKey = openKeys.find(key => this.openKeys.indexOf(key) === -1);
      this.state = 1
      if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
        console.log("关闭")
        this.state = 2
        this.openKeys = openKeys;
        console.log("关闭", this.menuSelect)
        // this.$router.push({  path: '/buyManage/BuyDataNew/1' })
        let menuSelect = Vue.ls.get(MenuSelect)
        if (menuSelect == 2) {
          this.$router.push({ name: 'SaleDataAmount' })
        } else if (menuSelect == 1) {
          this.$router.push({ name: 'BuyDataAmount' })
        } else if (menuSelect == 3) {
          this.$router.push({ name: 'StockIndex' })
        } else if (menuSelect == 4) {
          this.$router.push({ name: 'InvoiceIndex' })
        } else if (menuSelect == 5) {
          this.$router.push({ name: 'moneyIndex' })
        } else {

        }

      } else {

        this.openKeys = latestOpenKey ? [latestOpenKey] : [];
        if (this.openKeys == '/buyManage' && this.filterPermissMainIndex('method:query:purchase_manage')) {
          Vue.ls.set(MenuSelect, 1)
          this.$router.push({ name: 'BuyDataAmount' })
          this.updateMenu()
        } else if (this.openKeys == '/saleManage' && this.filterPermissMainIndex('method:query:sale_manage')) {
          Vue.ls.set(MenuSelect, 2)
          this.$router.push({ name: 'SaleDataAmount' })
          this.updateMenu()
        } else if (this.openKeys == '/stockManage' && this.filterPermissMainIndex('method:query:sale_order')) {
          Vue.ls.set(MenuSelect, 3)
          this.$router.push({ name: 'StockIndex' })
          this.updateMenu()
        } else if (this.openKeys == '/invoiceManage' && this.filterPermissMainIndex('method:query:invoice_index')) {
          Vue.ls.set(MenuSelect, 4)
          this.$router.push({ name: 'InvoiceIndex' })
          this.updateMenu()
        } else if (this.openKeys == '/MoneyManage' && this.filterPermissMainIndex('method:query:finance_manage_index')) {
          Vue.ls.set(MenuSelect, 5)
          this.$router.push({ name: 'moneyIndex' })
          this.updateMenu()
        } else {
          Vue.ls.set(MenuSelect, 6)
        }

      }
    },

    // select menu item
    // onOpenChange(openKeys) {

    //   console.log("隐藏",this.cachedOpenKey)
    //   console.log("开启",this.openKeys)

    //   // 非水平模式时
    //   const latestOpenKey = openKeys.find(key => !this.openKeys.includes(key))

    //   this.state=1
    //   if (!this.rootSubmenuKeys.includes(latestOpenKey)) {
    //     //伸缩回去时触发

    //     this.openKeys = openKeys

    //     this.$router.push({ name: 'BuyDataAmount' })

    //   } else {

    //     this.openKeys = latestOpenKey ? [latestOpenKey] : []
    //     this.selectMenuAnt =this.openKeys

    //     //塞入路由

    //     if (this.openKeys == '/buyManage') {
    //       this.state=2
    //       this.$router.push({ name: 'BuyDataAmount' })
    //     } else if (this.openKeys == '/saleManage') {
    //       this.state=2
    //       this.$router.push({ name: 'SaleDataAmount' })
    //     }


    //   }
    // },
    updateMenu() {
      console.log("开启")
      if (this.state == 1) {
        console.log("开启2")
        const routes = this.$route.matched.concat()


        const { hidden } = this.$route.meta

        if (routes.length >= 3 && hidden) {
          routes.pop()

          this.selectedKeys = [routes[routes.length - 1].path]

        } else {

          this.selectedKeys = [routes.pop().path]

        }
        const openKeys = []
        if (this.mode === 'inline') {




          routes.forEach(item => {
            openKeys.push(item.path)
          })


        }

        this.collapsed ? (this.cachedOpenKeys = openKeys) : (this.openKeys = openKeys)
      }


    },

    // render
    renderItem(menu) {
      if (!menu.hidden) {
        return menu.children && !menu.hideChildrenInMenu ? this.renderSubMenu(menu) : this.renderMenuItem(menu)
      }
      return null
    },
    renderMenuItem(menu) {
      const target = menu.meta.target || null
      const tag = target && 'a' || 'router-link'
      const props = { to: { name: menu.name } }
      const attrs = { href: menu.path, target: menu.meta.target }

      if (menu.children && menu.hideChildrenInMenu) {
        // 把有子菜单的 并且 父菜单是要隐藏子菜单的
        // 都给子菜单增加一个 hidden 属性
        // 用来给刷新页面时， selectedKeys 做控制用
        menu.children.forEach(item => {
          item.meta = Object.assign(item.meta, { hidden: true })
        })
      }

      return (
        <Item {...{ key: menu.path }}>
          <tag {...{ props, attrs }}>
            {this.renderIcon(menu.meta.icon)}
            <span>{menu.meta.title}</span>
          </tag>
        </Item>
      )
    },
    renderSubMenu(menu) {
      const itemArr = []
      if (!menu.hideChildrenInMenu) {
        menu.children.forEach(item => itemArr.push(this.renderItem(item)))
      }
      return (
        <SubMenu {...{ key: menu.path }}>
          <span slot="title">
            {this.renderIcon(menu.meta.icon)}
            <span>{menu.meta.title}</span>
          </span>
          {itemArr}
        </SubMenu>
      )
    },
    renderIcon(icon) {
      if (icon === 'none' || icon === undefined) {
        return null
      }
      const props = {}
      typeof (icon) === 'object' ? props.component = icon : props.type = icon
      return (
        <Icon {... { props }} />
      )
    }
  },

  render() {
    const { mode, theme, menu } = this
    const props = {
      mode: mode,
      theme: theme,
      openKeys: this.openKeys
    }
    const on = {
      select: obj => {
        this.selectedKeys = obj.selectedKeys
        this.$emit('select', obj)
      },
      openChange: this.onOpenChange
    }

    const menuTree = menu.map(item => {
      if (item.hidden) {
        return null
      }
      return this.renderItem(item)
    })
    // {...{ props, on: on }}
    return (
      <Menu vModel={this.selectedKeys} {...{ props, on: on }}>
        {menuTree}
      </Menu>
    )
  }
}
